package com.kku;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DietplannerActivity extends Activity {
	/** Called when the activity is first created. */
	WebView webView = null;
	Boolean checkFinish = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		DietplannerPlugin dietPlugin = new DietplannerPlugin();
		dietPlugin.setContext(this);

		setContentView(R.layout.splash);
		webView = new WebView(this);

		webView.setBackgroundColor(Color.WHITE);

		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setDatabaseEnabled(true);
		webView.getSettings().setDomStorageEnabled(true);

		webView.addJavascriptInterface(dietPlugin, "PLUGIN");

		webView.setWebViewClient(new WebViewClient() {
		});

		webView.getSettings().setDatabasePath(getApplicationContext().getDir("MDB", 0).getPath());

		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
				quotaUpdater.updateQuota(estimatedSize * 2);
			}

			@Override
			public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
				// TODO Auto-generated method stub
				return super.onJsAlert(view, url, message, result);
			}

			@Override
			public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
				// TODO Auto-generated method stub
				final Dialog jsConfirm = new Dialog(view.getContext());
				jsConfirm.requestWindowFeature(Window.FEATURE_NO_TITLE);
				jsConfirm.setContentView(R.layout.on_js_confirm);
				jsConfirm.setCancelable(true);

				jsConfirm.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

				TextView content = (TextView) jsConfirm.findViewById(R.id.content_label);

				content.setText(message);

				Button positiveBtn = (Button) jsConfirm.findViewById(R.id.positiveBtn);
				Button negativeBtn = (Button) jsConfirm.findViewById(R.id.negativeBtn);
				positiveBtn.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						result.confirm();
						jsConfirm.dismiss();
					}
				});
				negativeBtn.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						result.cancel();
						jsConfirm.dismiss();
					}
				});

				jsConfirm.setOnCancelListener(new OnCancelListener() {
					public void onCancel(DialogInterface dialog) {
						result.cancel();
						jsConfirm.dismiss();
					}
				});

				jsConfirm.show();

				return true;
			}

			@Override
			public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
				// TODO Auto-generated method stub
				return super.onJsPrompt(view, url, message, defaultValue, result);
			}
		});

		webView.loadUrl("file:///android_asset/www/food.html");
		webView.setHorizontalScrollBarEnabled(false);
		webView.setVerticalScrollBarEnabled(true);
		webView.setScrollBarStyle(33554432);
		webView.setScrollbarFadingEnabled(true);

		webView.requestFocus();
		webView.setFocusable(true);
		webView.setFocusableInTouchMode(true);
		webView.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_UP:
					if (!v.hasFocus()) {
						v.requestFocus();
					}
					break;
				}
				return false;
			}
		});

		Handler handle = new Handler();
		handle.postDelayed(new Runnable() {
			public void run() {
				// TODO Auto-generated method stub
				setContentView(webView);
			}
		}, 2000);
	}

	@Override
	public void onBackPressed() {
		if (webView.canGoBack()) {
			webView.goBack();
		} else if (!checkFinish) {
			Toast.makeText(this, "종료를 원하시면 한번더 클릭해 주세요.", 3000).show();
			checkFinish = true;
			Timer t = new Timer();
			t.schedule(new TimerTask() {
				public void run() {
					checkFinish = false;
				}
			}, 3000);
		} else if (checkFinish) {
			finish();
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		// Checks the orientation of the screen
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
		}
	}

	public void resultCamera(int i) {
		// 카메라 촬영을 할 수 있는 액티비티를 실행할 수 있도록 인텐트 객체를 생성한다.
		Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		// 인텐트 정보에 맞는 액티비티를 실행한다.
		startActivityForResult(intent, i);
	}

	public void resultAlbum(int i) {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_GET_CONTENT);
		intent.setType("image/-");
		startActivityForResult(intent, i);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 결과 값이 있고, 액티비티를 시작할 때 0로 설정해둔 결과값인 경우
		if (resultCode == RESULT_OK) {
			if (requestCode == DietplannerPlugin.ADD_PICTURE) {
				// intent 의 여분 데이터로 저장된 비트맵 이미지를 얻는다.
				Bitmap bmp = (Bitmap) data.getExtras().get("data");

				File imDirectory = new File(getDir("picture", Activity.MODE_PRIVATE).getPath());
				File imDirectory2 = new File(Environment.getExternalStorageDirectory().getPath() + "/newFolder");

				if (!imDirectory2.exists()) {
					imDirectory2.mkdir();
					try {
						imDirectory2.createNewFile();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				FileOutputStream fileOutputStream = null;
				String nameFile;

				nameFile = String.valueOf(new SimpleDateFormat("yyyyMMdd").format(new Date()));
				String location = imDirectory2.toString() + "/" + nameFile + ".jpg";
				try {
					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inSampleSize = 5;

					fileOutputStream = new FileOutputStream(location);

					BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
					
					int iHeight = bmp.getHeight();
					int iWidth = bmp.getWidth();

					while (iHeight > 800 || iWidth > 800) {
						iHeight = iHeight * 3 / 4;
						iWidth = iWidth * 3 / 4;
					}

					Bitmap tmpSrc = Bitmap.createScaledBitmap(bmp, iWidth, iHeight, false);
					
					tmpSrc.compress(CompressFormat.JPEG, 90, bos);

					bos.flush();
					bos.close();

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				JSONObject result = new JSONObject();
				try {
					result.put("location", location);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				((DietplannerPlugin) DietplannerPlugin.MyContext).pluginInterface(result);

			} else if (requestCode == DietplannerPlugin.GET_PICTURE) {
				JSONObject result = new JSONObject();

				Cursor c = getContentResolver().query(data.getData(), null, null, null, null);
				c.moveToNext();
				String path = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA));
				c.close();

				String nameFile;
				nameFile = String.valueOf(new SimpleDateFormat("yyyyMMdd").format(new Date()));
				
				String location = "";
				location = Environment.getExternalStorageDirectory().getPath() + "/newFolder/" + nameFile + ".jpg";

				File goalFile = new File(location);
				FileOutputStream goal;

				try {
					Bitmap originalImage = BitmapFactory.decodeFile(path);

					int iHeight = originalImage.getHeight();
					int iWidth = originalImage.getWidth();

					while (iHeight > 800 || iWidth > 800) {
						iHeight = iHeight * 3 / 4;
						iWidth = iWidth * 3 / 4;
					}

					Bitmap tmpSrc = Bitmap.createScaledBitmap(originalImage, iWidth, iHeight, false);
					
					goal = new FileOutputStream(goalFile);
					tmpSrc.compress(Bitmap.CompressFormat.JPEG, 90, goal);

					goal.close();

					result.put("location", location);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				((DietplannerPlugin) DietplannerPlugin.MyContext).pluginInterface(result);
			}
		}
		else {
			((DietplannerPlugin) DietplannerPlugin.MyContext).pluginInterface(null);
		}
	}
}